package com.hkfn.rfb.common.utils;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.CLIPBOARD_SERVICE;
import static android.content.Context.TELEPHONY_SERVICE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.hkfn.rfb.common.bean.ConstData;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

public class Utils {
    /**
     * 版本名
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 版本号
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        }
        catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取设备IMEI
     * @param context
     * @return 设备IMEI
     * */
    public static String getIMEI(Context context) {
        try {
            String imei = PreferencesUtils.getString(context, ConstData.DEVICE_IMEI);
            if (StringUtils.isEmpty(imei)) {
                TelephonyManager tm = (TelephonyManager) context
                        .getSystemService(TELEPHONY_SERVICE);
                if (tm != null) {
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                        return "";
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        try {
                            imei = tm.getImei(0);
                        } catch (Exception e) {
                            imei = tm.getImei();
                        }
                    } else {
                        imei = tm.getDeviceId();
                    }
                    if (!StringUtils.isEmpty(imei)){
                        PreferencesUtils.putString(context, ConstData.DEVICE_IMEI, imei);
                    }
                }
            }
            if (null == imei){
                imei = "";
            }
            return imei;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取androidID
     * @return
     */
    public static String getAndroidID(Context context){
        return Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID);
    }

    /**
     * 隐藏输入键盘
     * @param view
     * @param context
     */
    public static void hideSoftInput(View view, Context context) {
        if (null != view) {
            InputMethodManager inputMeMana = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMeMana.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public static void hideKeyboard(Activity activity) {
        try {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            //Find the currently focused view, so we can grab the correct window token from it.
            View view = activity.getCurrentFocus();
            //If no view currently has focus, create a new one, just so we can grab a window token from it
            if (view == null) {
                view = new View(activity);
            }
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }catch (Exception e){}
    }

    /**
     * 显示软键盘
     */
    public static void showSoftInput(Context context) {
        InputMethodManager inputMeMana = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMeMana.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 根据手机分辨率从dp转成px
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率�?px(像素) 的单�?转成�?dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param fontScale（DisplayMetrics类中属�?scaledDensity�?
     * @return
     */
    public static int px2sp(float pxValue, float fontScale) {
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param fontScale（DisplayMetrics类中属�?scaledDensity�?
     * @return
     */
    public static int sp2px(float spValue, float fontScale) {
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取文字宽度
     * @param textSize
     * @param textStr
     * @return
     */
    public static float getTextViewContentLength(int textSize, String textStr) {
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        return paint.measureText(textStr);
    }


    /**
     * 复制到剪切板
     * @param copyStr 复制内容
     * @param copyTip 提示内容
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public static void copyToClipBoard(Activity activity, String copyStr, String copyTip) {
        if (Build.VERSION.SDK_INT < 11) {
            return;
        }

        if (!StringUtils.isEmpty(copyStr)) {
            ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(CLIPBOARD_SERVICE);
            clipboard.setText(copyStr);
            if (!StringUtils.isEmpty(copyTip)) {
                Toast.makeText(activity, copyTip, Toast.LENGTH_LONG).show();
            }
        }
    }


    /**
     * 根据包名判断apk是否已安装
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }

        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> pName = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                if((pinfo.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)==0) {
                    //如果非系统应用，则添加至appList
                    String pn = pinfo.get(i).packageName;
                    pName.add(pn);
                }
            }
        }
        //判断pName中是否有目标程序的包名，有TRUE，没有FALSE
        return pName.contains(packageName);
    }

    public static String md5(List<String> params) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : params) {
            stringBuffer.append(str);
        }
        try {
            byte[] intputBytes = stringBuffer.toString().getBytes("UTF-8");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] hash = md5.digest(intputBytes);
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) hex.append("0");
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }catch (Exception e) {
            return null;
        }
    }

    public static String md5(String content) {
        if (StringUtils.isEmpty(content)){
            return "";
        }
        try {
            byte[] intputBytes = content.getBytes("UTF-8");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] hash = md5.digest(intputBytes);
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) hex.append("0");
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断是否存在可用网络
     */
    public static boolean hasNetwork(Context context) {
        android.net.ConnectivityManager cManager = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo info = cManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 判断sdcard是否可用
     * @return true为可用，否则为不可用
     */
    public static boolean sdCardIsAvailable() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED))
            return false;
        return true;
    }

    /**
     * 从网络下载图片并保存到指定路径
     * @param imgUrl
     * @param filePath
     */
    public static void downloadImageAndSave(String imgUrl, String filePath) throws Exception{
        URL url;
        InputStream is = null;
        FileOutputStream fos = null;
        HttpURLConnection conn;
        try {
            url = new URL(imgUrl);
            conn = (HttpURLConnection) url.openConnection();
            //判定是否会进行302重定向
            if (302 == conn.getResponseCode()) {
                //如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
                String location = conn.getHeaderField("Location");
                url = new URL(location);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
            }

            if(200 == conn.getResponseCode()){
                is = conn.getInputStream();
                File file = new File(filePath);
                fos = new FileOutputStream(file);
                Utils.copyStream(is, fos);
            }
        }
        catch (Exception e) {
            throw e;
        }
        finally {
            try {
                is.close();
                fos.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 拷贝流
     * @param is
     * @param os
     */
    public static void copyStream(InputStream is, OutputStream os) throws IOException {
        if (is == null || os == null) {
            return;
        }

        BufferedInputStream bufIs;
        boolean shouldClose = false;
        if (is instanceof BufferedInputStream) {
            bufIs = (BufferedInputStream) is;
        }
        else {
            bufIs = new BufferedInputStream(is);
            shouldClose = true;
        }

        int bufLen = 102400;
        byte[] buf = new byte[bufLen];
        int len;
        while (true) {
            len = bufIs.read(buf);
            if (len < 0) {
                break;
            }
            os.write(buf, 0, len);
        }
        if (shouldClose) {
            bufIs.close();
        }
    }

    /**
     * 防止重复点击
     * @return
     */
    public static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ( 0 < timeD && timeD < 1000) {
            return true;
        }
        return false;
    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 校验密码格式 6-16个字符,不包含空格,必须包含数字,字母两种
     * @param password
     * @return
     */
    public static boolean chechPsIsTrue(String password){
        if (StringUtils.isEmpty(password)){
            return false;
        }
        return Pattern.matches("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$", password);
    }

    /**
     * 校验手机号
     * @param phoneNumber
     * @return
     */
    public static boolean checkPhoneNumber(String phoneNumber){
        if (StringUtils.isEmpty(phoneNumber)){
            return false;
        }
        return Pattern.matches("^(1[0-9][0-9])\\d{8}$", phoneNumber);
    }

    /**
     * 校验邮箱
     * @param email
     * @return
     */
    public static boolean checkEmail(String email){
        if (StringUtils.isEmpty(email)){
            return false;
        }
        return Pattern.matches("^(\\s*)|\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", email);
    }

    /**
     * 数字转汉字
     * @param number
     * @return
     */
    public static String convert(int number) {
        String[] single = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};//汉字一到九
        String[] unit = {"", "十", "百", "千", "万", "亿"};//汉字单位
        StringBuilder sb = new StringBuilder();
        int[] unitInt = {100000000, 10000, 1000, 100, 10};
        int m = 0;
        int tmp = -1;
        for (int i : unitInt) {

            int n = number / i;
            number = number % i;
            if (sb.length() != 0 || n != 0) {
                if (n > single.length - 1) {
                    String cc = convert(n);
                    sb.append(cc);
                } else {
                    if (0==tmp && 0==n) {

                    } else {
                        sb.append(single[n]);
                    }

                    tmp = n;
                }
                if (n != 0) {
                    sb.append(unit[unit.length - 1 - m]);
                }

            }
            m++;

        }
        if (number != 0) {
            sb.append(single[number]);
        }
        String ret = sb.toString();
        if (ret.length()==0){
            return "零";
        }
        String last = String.valueOf(ret.charAt(ret.length() - 1));
        if ("零".equals(last)) {
            ret = ret.substring(0, ret.length() - 1);
        }

        return ret;
    }

    /**
     * 栈内是否存在activity
     * @param activity
     * @param context
     * @return
     */
    public static boolean isExistMainActivity(Class<?> activity, Context context) {
        try {
            Intent intent = new Intent(context, activity);
            ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
            boolean flag = false;
            if (cmpName != null) { // 说明系统中存在这个activity    
                ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
                List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);//
                for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                    if (taskInfo.baseActivity.equals(cmpName)) {// 说明它已经启动了
                        flag = true;
                        break;//跳出循环，优化效率
                    }
                }
            }
            return flag;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 字节数组转字符串
     * @param inarray
     * @return
     */
    public static String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";
        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    //删除文件夹和文件夹里面的文件
    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    /**
     * BBC异或校验
     * @param hex
     * @return
     */
    public static String getBCC(String hex) {
        int i = 0, j = 0;
        int len = hex.length();
        short inb[] = new short[len];
        for (i = 0; i < len; i++) {
            inb[i] = charToHex(hex.charAt(i));   //将String里的每一个char转换为Hex
        }

        for (i = 0; i < len; i++) {    //将每两个Hex合并成一个byte
            inb[j] = (byte) (((inb[i] << 4) & 0x00f0) | ((inb[i + 1]) & 0x000f));
            i++;
            j++;
        }
        byte temp = 0x00; //校验值
        for (i = 0; i < len / 2; i++) { //异或
            temp ^= inb[i];
        }
        byte[] bytes = new byte[1];
        bytes[0] = temp;
        return HexUtil.BinaryToHexString(bytes).replace(" ", "");
    }

    public static short charToHex(char x) { //将单个char转换为Hex
        short result = 0;
        switch (x) {
            case 'a':
                result = 10;
                break;
            case 'b':
                result = 11;
                break;
            case 'c':
                result = 12;
                break;
            case 'd':
                result = 13;
                break;
            case 'e':
                result = 14;
                break;
            case 'f':
                result = 15;
                break;
            case 'A':
                result = 10;
                break;
            case 'B':
                result = 11;
                break;
            case 'C':
                result = 12;
                break;
            case 'D':
                result = 13;
                break;
            case 'E':
                result = 14;
                break;
            case 'F':
                result = 15;
                break;
            default:
                result = (short) Character.getNumericValue(x);
                break;
        }
        return result;
    }

    /**
     * 获取用户IP地址<br/>
     * 注意：需要在androidManifest.xml中声明下面三个权限才能正常使用该方法，否则会空指针异常
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     * <uses-permission android:name="android.permission.INTERNET"/>
     */
    public static String getIpAddress(Context context) {
        if (context == null) {
            return "";
        }

        ConnectivityManager conMann = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileNetworkInfo.isConnected()) {
            return getLocalIpAddress();
        } else if (wifiNetworkInfo.isConnected()) {
            return getWifiAddress(context);
        }
        return "";
    }

    private static String getLocalIpAddress() {
        try {
            ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : nilist) {
                ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                for (InetAddress address : ialist) {
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        return address.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String getWifiAddress(Context context) {
        if (context == null) {
            return "";
        }
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return intToIp(ipAddress);
    }

    private static String intToIp(int ipInt) {
        return (ipInt & 0xFF) + "." +
                ((ipInt >> 8) & 0xFF) + "." +
                ((ipInt >> 16) & 0xFF) + "." +
                ((ipInt >> 24) & 0xFF);
    }

    /**
     * 获取网关(API>=29)
     */
    public static String getGateway(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
        int gateway = dhcpInfo.gateway;
        return Formatter.formatIpAddress(gateway);
    }
    /**
     * 获取rssi
     */
    public static int getRssi(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.getConnectionInfo().getRssi();
    }

    /**
     * 获取dns
     */
    public static String getDns() {

        String[] dnsServers = getDnsFromCommand();
        // 组装
        StringBuffer sb = new StringBuffer();
        if (dnsServers != null) {
            sb.append(dnsServers[0]);  //注意这里只会返回1个dns服务器ip
        }
        return sb.toString();
    }


    //通过 getprop 命令获取
    private static String[] getDnsFromCommand() {
        LinkedList<String> dnsServers = new LinkedList<>();
        try {
            Process process = Runtime.getRuntime().exec("getprop");
            InputStream inputStream = process.getInputStream();
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = lnr.readLine()) != null) {
                int split = line.indexOf("]: [");
                if (split == -1) continue;
                String property = line.substring(1, split);
                String value = line.substring(split + 4, line.length() - 1);
                if (property.endsWith(".dns")
                        || property.endsWith(".dns1")
                        || property.endsWith(".dns2")
                        || property.endsWith(".dns3")
                        || property.endsWith(".dns4")) {
                    InetAddress ip = InetAddress.getByName(value);
                    if (ip == null) continue;
                    value = ip.getHostAddress();
                    if (value == null) continue;
                    if (value.length() == 0) continue;
                    dnsServers.add(value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
    }

    /**
     * 获取Sim卡CCID
     * @return
     */
    public static String getSimCCID(Context context){
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            String iccid = telephonyManager.getSimSerialNumber();
            return iccid;
        }catch (Exception e){
            return "";
        }
    }

    public static void showToastAndLogText(final Activity activity, final String content){
        if (StringUtils.isEmpty(content)){
            return;
        }
        if (ConstData.INNER){
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast(activity, content);
                }
            });
        }
        Log.e("xuhan", content);
    }


    /**
     * 获取格位控制器联系地址
     * @return
     */
    public static String getCaseCommunicationAddress(int caseNumber){
        return HexUtil.int10ToHex(128 + caseNumber, 2);
    }

    /**
     * 重启系统
     */
    public static void rebootSystem() {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
            outputStream.writeBytes("/system/bin/reboot\n");
            outputStream.flush();
            outputStream.writeBytes("exit\n");
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏显示底部导航栏
     */
    public static void showOrHideNav(Activity activity, boolean needHide){
        Intent intent = new Intent();
        intent.setAction("com.android.intent.action.NAVBAR_SHOW");
        if (!needHide) {
            intent.putExtra("cmd", "show");
            PreferencesUtils.putBoolean(activity, ConstData.NAV_HIDE_FLAG, false);
            // Android 11+
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                WindowInsetsController controller = activity.getWindow().getInsetsController();
                if (controller != null) {
                    controller.show(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
                    controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
                }
            }
        }else {
            intent.putExtra("cmd", "hide");
            PreferencesUtils.putBoolean(activity, ConstData.NAV_HIDE_FLAG, true);
            // Android 11+
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                WindowInsetsController controller = activity.getWindow().getInsetsController();
                if (controller != null) {
                    controller.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
                    controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
                }
            }
        }
        activity.sendOrderedBroadcast(intent, null);



    }


    /**
     * 开启关闭飞行模式
     * @param enable
     */
    public static void setAirPlaneMode(Context context, boolean enable) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);
        } else {
            Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
        }
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", enable);
        context.sendBroadcast(intent);
    }
}
